package wp.ggt.com.myapplication;

import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import wp.ggt.com.myapplication.bean.FolderBean;

public class MainActivity extends AppCompatActivity {

    private GridView gv;
    private List<String> imageDatas ;
    private List<FolderBean> folderDatas = new ArrayList<>();
    private ProgressDialog pb;
    private int currentImgCount;
    private File currentDir;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            data2View();
        }
    };

    private void data2View() {
        if (currentDir==null){
            Toast.makeText(MainActivity.this, "没有扫描到任何图片", Toast.LENGTH_SHORT).show();
        }else{
            imageDatas= Arrays.asList(currentDir.list());
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initDatas();
        initEvent();
    }

    private void initEvent() {

    }

    /**
     * 利用ContentProvider扫描手机中的图片
     */

    private void initDatas() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            pb = ProgressDialog.show(this, null, "正在加载中");
            new Thread() {
                @Override
                public void run() {
                    Uri mImgUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                    ContentResolver contentResolver = MainActivity.this.getContentResolver();
                    Cursor cursor = contentResolver.query(mImgUri, null, MediaStore.Images.Media.MIME_TYPE + "=?or" + MediaStore.Images.Media.MIME_TYPE + "=?", new String[]{"image/jpeg", "image/png"}, MediaStore.Images.Media.DATE_MODIFIED);
                    Set<String> mDirPaths = new HashSet<>();
                    assert cursor != null;
                    while (cursor.moveToNext()) {
                        String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                        File parentFile = new File(path).getParentFile();
                        if (parentFile == null)
                            continue;
                        String dirPath = parentFile.getAbsolutePath();
                        FolderBean folderBean;
                        if (!mDirPaths.contains(dirPath)) {
                            mDirPaths.add(dirPath);
                            folderBean = new FolderBean();
                            folderBean.setDir(dirPath);
                            folderBean.setFirstImagePath(path);
                            if (parentFile.list() != null) {
                                int picSize = parentFile.list(new FilenameFilter() {
                                    @Override
                                    public boolean accept(File dir, String filename) {
                                        return filename.endsWith(".jpg") || filename.endsWith("png") || filename.endsWith(".jpeg");
                                    }
                                }).length;
                                folderBean.setCount(picSize);
                                if (picSize > currentImgCount) {
                                    currentDir = parentFile;
                                }
                            }
                            folderDatas.add(folderBean);
                        }
                    }
                    cursor.close();
                    //通知扫描完成
                    handler.sendEmptyMessage(1);
                }
            }.start();
        } else {
            Toast.makeText(MainActivity.this, "当前存储卡不可用", Toast.LENGTH_SHORT).show();
        }
    }

    private void initView() {
        gv = (GridView) findViewById(R.id.gv_photo);
    }
    
    class ImageAdapter extends BaseAdapter{
        private List<String> imageDatas;
        private LayoutInflater layoutInflater;
        private String dirPath;
        
        public ImageAdapter(Context context,List<String> imageDatas,String dirPath){
            layoutInflater=LayoutInflater.from(context);
            this.imageDatas=imageDatas;
            this.dirPath=dirPath;
        }

        @Override
        public int getCount() {
            return imageDatas.size();
        }

        @Override
        public Object getItem(int position) {
            return imageDatas.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imageView;
            if (convertView==null){
                convertView=layoutInflater.inflate(R.layout.gv_item,null);
                imageView= (ImageView) convertView.findViewById(R.id.iv_item);
                convertView.setTag(imageView);
            }else{
                imageView= (ImageView) convertView.getTag();
            }
                
            return convertView;
        }
        
        
        
    }
}
